package com.samp.bblock.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.util.StringUtils;

public class DateUtils {
	
	//标准时间格式
	public static final String STANDARD_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	//标间日期格式
	public static final String STANDARD_DATE_FORMAT = "yyyy-MM-dd";
	
	/**
	 * 检查字符串类型日期是否是正确的格式。
	 * @param date
	 * @return
	 */
	public static boolean isRightDateStr(String date){
		if( StringUtils.isEmpty(date) ){
			return false;
		}
		DateFormat formatter = new SimpleDateFormat(STANDARD_TIME_FORMAT);
		try{  
            formatter.parse(date);  
            return true;
        }catch(Exception e){
            return false;
        }
	}
	
	/**
	 * 将字符串格式化为标准时间
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date parseStandardDate(String date) throws ParseException{
		if( StringUtils.isEmpty(date) ){
			return null;
		}
		DateFormat formatter = new SimpleDateFormat(STANDARD_TIME_FORMAT);
        return formatter.parse(date);
	}
	
	/**
	 * 将时间格式化为标准字符串。
	 * @param date
	 * @return
	 */
	public static String formatStandardDate(Date date){
		if( date == null ){
			return null;
		}
		DateFormat formatter = new SimpleDateFormat(STANDARD_TIME_FORMAT);
		return formatter.format(date);
	}
	
	/**
	 * 获取给定时间提前days天的时间。<br>
	 * 
	 * @param date
	 * @param days
	 * @return
	 */
	public static Date beforeDates(Date date , Integer days){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, days*-1);
		return c.getTime();
	}
	
	public static Date beforeSeconds(Date date , Integer seconds){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.SECOND, seconds*-1);
		return c.getTime();
	}
	
	public static void main(String[] args) {
		Date date = new Date();
		Date date2 = beforeSeconds(date, 1);
		System.out.println(formatStandardDate(date));
		System.out.println(formatStandardDate(date2));
	}
	
}
